
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

/**
 * 
 * @author Igor Covganet
 * @Created Jul 7, 2010
 * 
 *          This class is supposed to be in the project of marathon to be used.
 * 
 *          In package app has to be class with solution to the marathon only!
 *          It will create a backup file in folder backup/ of the project, and
 *          the sources will be saved with name src[version].txt The result will
 *          go in folder res/ of the project.
 */
public class BackupAdmin {
	private static PrintWriter pw = null;
	private static int fileNr = 0;
	
	private static File sourceFile = null;

	public static void saveResultVerbose(String result, String className) {
		saveResult(result, className);
		System.out.println(result);
	}
	
	public static void saveResultVerbose(String result) {
		saveResult(result);
		System.out.println(result);
	}

	public static void saveResult(String result, String className) {
		sourceFile = new File("src/" + className + ".java");
		saveResult(result);
	}
	
	public static void saveResult(String result) {
		try {
			if(fileNr == 0) {
				if(!new File("backup/").exists()) {
					new File("backup/").mkdir();
				}
				if(!new File("res/").exists()) {
					new File("res/").mkdir();
				}
				File[] fls = new File("src/").listFiles();
				if(sourceFile == null) {
					for(int i = 0; i < fls.length; i++) {
						String name = fls[i].getName();
						if(name.endsWith("Vis.java")) {
							sourceFile = new File("src/" + fls[i].getName().substring(0, name.length() - 8) + ".java");
							System.out.println(sourceFile.getName());
						}
					}
				}
				fileNr = 1;
				while(new File("backup/src" + fileNr + ".txt").exists()) {
					fileNr++;
				}
				pw = new PrintWriter(new FileWriter("backup/src" + fileNr + ".txt"));
				BufferedReader br = new BufferedReader(new FileReader(sourceFile));
				String str = null;
				boolean descPrinted = false;
				while((str = br.readLine()) != null) {
					if(str.trim().equals("package app;")) {
						pw.println(str);
						pw.println("/** Version " + fileNr + " */");
						descPrinted = true;
					} else if(str.trim().length() > 0 && !descPrinted) {
						pw.println("/** Version " + fileNr + " */");
						descPrinted = true;
						pw.println(str);
					} else {
						pw.println(str);
					}
				}
				br.close();
				pw.close();
				pw = new PrintWriter(new FileWriter("res/res" + fileNr + ".txt"));
			}
			pw.println(result);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public static void closeWriterVerbose(String finalStatement) {
		System.out.println(finalStatement);
		closeWriter(finalStatement);
	}
	
	/**
	 * The user is responsible to call this function at the end of the loop, in
	 * order to save the data and close the stream
	 */
	public static void closeWriter(String finalStatement) {
		pw.println(finalStatement);
		pw.close();
	}
}